<?php

namespace app\controller;

use Overtrue\Pinyin\Pinyin;


class Users extends Base
{

    public function initialize()
    {
        parent::initialize();
        Token::apisecurity();
    }


    public function users()
    {
        $where = [];
        $where[] = ['delete_time', '=', 0];
        $where[] = ['id', '=', _get()['id']];
        $result = db('users', 'mysql')->withoutField('truepass')->where($where)->find();
        $company = db('company')->select()->toArray();
        $department = db('department')->select()->toArray();
        $position = db('position')->select()->toArray();
        $positionarr = [];
        foreach ($department as $key => $value) {
            foreach ($position as $v) {
                if ($value['id'] == $v['department_id']) {
                    $positionarr[$value['department_name']]['child'][] = $v;
                }
            }
        }
        $view = [
            'info' => $result,
            'company' => $company,
            'department' => $department,
            'position' => $positionarr,
        ];
        return view('', $view);
    }

    /**
     * 员工列表
     * api post /users/index
     * @param int id 员工ID
     * @param int department_id 部门ID
     * @param int position_id 职位ID
     * @param int company_id 公司ID
     * @param int page 分页 默认1
     * @return json
     */
    public function index()
    {
        if (_isget()) {
            if ((isset(_get()['id']) && _get()['id'])) {
                $where = [];
                $where[] = ['delete_time', '=', 0];
                $where[] = ['id', '=', _get()['id']];
                $result = db('users', 'mysql')->withoutField('truepass')->where($where)->find();
                if (!$result) {
                    _Error('员工不存在');
                }
                $result['create_time'] = totime($result['create_time']);
                $result['update_time'] = totime($result['update_time']);
                $result['company'] = db('company', 'mysql')->where('id', $result['company_id'])->value('company_name');
                $result['company'] = db('company', 'mysql')->where('id', $result['company_id'])->value('company_name');
                $result['position'] = db('position', 'mysql')->where('id', 'in', @array_filter(str2arr($result['position_id'])))->field('position_name')->select()->toArray();
                $result['department'] = db('department', 'mysql')->where('id', 'in', @array_filter(str2arr($result['department_id'])))->field('department_name')->select()->toArray();
                $result['level_cn'] = getLevel($result['level']);
                _Success('员工详情', 200, $result);
            } else {
                $where = [];
                $where[] = ['delete_time', '=', 0];

                if (isset(_get()['department_id']) && _get()['department_id']) {
                    $where[] = ['department_id', '=', _get()['department_id']];
                }
                if (isset(_get()['company_id']) && _get()['company_id']) {
                    $where[] = ['company_id', '=', _get()['company_id']];
                }
                if (isset(_get()['position_id']) && _get()['position_id']) {
                    $where[] = ['position_id', 'like', "%," . _get()['position_id'] . ",%"];
                }
                $limit = 16;
                if (isset(_get()['limit']) && _get()['limit']) {
                    $limit = _get()['limit'];
                }
                if (isset(_get()['type']) && _get()['type'] == 'all') {
                    $list = db('users','mysql')->withoutField('truepass')->where($where)->order('initials asc,pinyin asc')->select()->toArray();
                    $list = array_group($list, 'initials');
                    _Success('员工列表', 200, $list);
                } else {
                    $list = db('users', 'mysql')->withoutField('truepass')->where($where)->paginate($limit, false, ['query' => input()])->each(function ($item) {
                        $item['create_time'] = totime($item['create_time']);
                        $item['update_time'] = totime($item['update_time']);
                        $item['company'] = db('company', 'mysql')->where('id', $item['company_id'])->value('company_name');
                        $item['company'] = db('company', 'mysql')->where('id', $item['company_id'])->value('company_name');
                        $item['position'] = db('position', 'mysql')->where('id', 'in', @array_filter(str2arr($item['position_id'])))->field('position_name')->select()->toArray();
                        $item['department'] = db('department', 'mysql')->where('id', 'in', @array_filter(str2arr($item['department_id'])))->field('department_name')->select()->toArray();
                        $item['level_cn'] = getLevel($item['level']);
                        return $item;
                    })->toArray();
                    _Success('员工列表', 200, $list['data']);
                }
            }
        }
        _Result('响应失败', 500);
    }

    /**
     * 添加员工
     * api post /users/users_add
     * @param string nickname
     * @param string account
     * @param int password
     * @param int company_id
     * @param int department_id
     * @param int position_id
     * @param int level
     * @return json
     */
    public function users_add()
    {
        if (_ispost()) {
            if (!isset(_post()['nickname']) || !_post()['nickname']) {
                _Error('员工姓名未填写');
            }
            if (!isset(_post()['account']) || !_post()['account']) {
                _Error('员工登陆账号未填写');
            }
            if (!isset(_post()['password']) || !_post()['password']) {
                _Error('员工登陆密码未填写');
            }
            if (!isset(_post()['department_id']) || !_post()['department_id']) {
                _Error('部门未选择');
            }
            if (!isset(_post()['company_id']) || !_post()['company_id']) {
                _Error('公司未选择');
            }
            $company = db('company', 'mysql')->where('id', _post()['company_id'])->find();
            if (!$company) {
                _Error('公司不存在');
            }
            // if (!isset(_post()['position_id']) || !_post()['position_id']) {
            //     _Error('职位未选择');
            // }
            if (db('users', 'mysql')->where('account', _post()['account'])->find()) {
                _Error('用户名已存在');
            }

            $data = _post();
            if (is_array($data['department_id'])) {
                $data['department_id'] = arr2str($data['department_id']);
            }
            if (isset(_post()['position_id']) && _post()['position_id']) {
                if (is_array($data['position_id'])) {
                    $data['position_id'] = arr2str($data['position_id']);
                }
            }

            $data['salt'] = rand_string();
            $data['truepass'] = $data['password'];
            $data['unionid'] = uniqid(md5(rand_string(12)));
            $data['password'] = pdk_encrypt($data['password'], $data['salt']);

            $data['company_name'] = $company['company_name'];
            if (isset(_post()['position_id']) && _post()['position_id']) {

                $data['position_name'] = arr2str(db('position', 'mysql')->where('id', 'in', str2arr($data['position_id']))->column('position_name'));
            }
            $data['department_name'] = arr2str(db('department', 'mysql')->where('id', 'in', str2arr($data['department_id']))->column('department_name'));

            if (isset(_post()['position_id']) && _post()['position_id']) {
                $data['position_id'] = '0,' . $data['position_id'] . ',';
            }else{
                $data['position_id'] = '0,';
            }
            $data['department_id'] = '0,' . $data['department_id'] . ',';



            $data['create_time'] = time();
            $data['update_time'] = time();
            $pinyin = new Pinyin();
            $name = mb_substr($data['nickname'], 0, 1, 'utf-8');
            $data['surname'] = $name;
            $data['initials'] = ucwords($pinyin->abbr($name));
            $result = db('users', 'mysql')->cache('getUsersSelect')->insert($data);
            if (!$result) {
                _Error('添加失败');
            }
            return _Success('添加成功');
        }
        _Result('响应失败', 500);
    }

    /**
     * 更新员工
     * api post /users/users_edit
     * @param int id 员工ID
     * @param string position_name 员工名称
     * @param string position_desc 员工描述
     * @return json
     */
    public function users_edit()
    {

        if (_ispost()) {
            if (!isset(_post()['id']) || !_post()['id']) {
                _Error('员工主键未提交');
            }
            if (!isset(_post()['nickname']) || !_post()['nickname']) {
                _Error('员工姓名未填写');
            }

            if (!isset(_post()['department_id']) || !_post()['department_id']) {
                _Error('部门未选择');
            }
            if (!isset(_post()['company_id']) || !_post()['company_id']) {
                _Error('公司未选择');
            }
            $company = db('company', 'mysql')->where('id', _post()['company_id'])->find();

            if (!$company) {
                _Error('公司不存在');
            }
            // if (!isset(_post()['position_id']) || !_post()['position_id']) {
            //     _Error('职位未选择');
            // }

            $data = _post();

            if (is_array($data['department_id'])) {
                $data['department_id'] = arr2str($data['department_id']);
            }
            if (isset(_post()['position_id']) && _post()['position_id']) {
                if (is_array($data['position_id'])) {
                    $data['position_id'] = arr2str($data['position_id']);
                }
            }

            if (isset($data['account']) && $data['account']) {
                unset($data['account']);
            }
            if (isset($data['password']) && $data['password']) {
                $data['salt'] = rand_string();
                $data['truepass'] = $data['password'];
                $data['password'] = pdk_encrypt($data['password'], $data['salt']);
            }

            $data['company_name'] = $company['company_name'];
            if (isset(_post()['position_id']) && _post()['position_id']) {
                $data['position_name'] = arr2str(db('position', 'mysql')->where('id', 'in', str2arr($data['position_id']))->column('position_name'));
            }

            $data['department_name'] = arr2str(db('department', 'mysql')->where('id', 'in', str2arr($data['department_id']))->column('department_name'));

            if (isset(_post()['position_id']) && _post()['position_id']) {
                $data['position_id'] = '0,' . $data['position_id'] . ',';
            }else{
                $data['position_id'] = '0,';
            }

            $data['department_id'] = '0,' . $data['department_id'] . ',';
            $data['update_time'] = time();
            $pinyin = new Pinyin();
            $name = mb_substr($data['nickname'], 0, 1, 'utf-8');
            $data['surname'] = $name;
            $data['initials'] = ucwords($pinyin->abbr($name));
            // halt($data);
            $result = db('users', 'mysql')->cache('getUsersSelect')->where('id', $data['id'])->update($data);
            if (!$result) {
                _Error('更新失败');
            }
            return _Success('更新成功');
        }
        _Result('响应失败', 500);
    }

    /**
     * 删除员工
     * @param int id 员工ID
     */
    public function users_del()
    {
        if (_ispost()) {
            if (!isset(_post()['id']) || !_post()['id']) {
                _Error('员工主键未提交');
            }
            // if(db('users','mysql')->where('position_id','like',"%,"._post()['id'].",%")->find()){
            //     _Error('员工下有员工信息');
            // }
            // if(db('users','mysql')->where('parent_id',_post()['id'])->find()){
            //     _Error('员工下有次级员工');
            // }
            //验证员工是否可删除
            $result = db('users', 'mysql')->where('id', _post()['id'])->cache('getUsersSelect')->delete();
            if (!$result) {
                _Error('删除失败');
            }
            return _Success('删除成功');
        }
        _Result('响应失败', 500);
    }
}
